﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SeDuce.BLL;
using SeDuce.DAL;
using SeDuce.Model;
using SeDuce.Utility;
using System.IO;

public partial class Management_Common_Brand : PagerBase
{
    List<Brand> brands = new List<Brand>();

    Lazy_Yu<BrandBLL> lazyBrandBLL = new Lazy_Yu<BrandBLL>(() => new BrandBLL());
    public BrandBLL LazyBrandBLL
    {
        get { return this.lazyBrandBLL.Value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        this.RegistrPager(this.GridView1, this.rptPageFliper, 7, this.FillPageMoudle(5000, SeDuce.DAL.BrandDAL.sqlGetBrands, new List<SortField>() { 
            new SortField() { FieldName = "Sort", DESC = false }
        }));
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "MOD")
        {
            try
            {
                GridViewRow row = ((LinkButton)e.CommandSource).Parent.Parent as GridViewRow;
                string strID = ((Label)this.GridView1.Rows[row.RowIndex].Cells[1].FindControl("lblID")).Text.Trim();
                string strName = ((Label)this.GridView1.Rows[row.RowIndex].Cells[2].FindControl("lblName")).Text.Trim();
                string strLogoPath = ((Image)this.GridView1.Rows[row.RowIndex].Cells[3].FindControl("imgLogo")).ImageUrl.Trim();
                string oldLogo = ((HiddenField)this.GridView1.Rows[row.RowIndex].Cells[3].FindControl("hidLogo")).Value.Trim();


                this.lblID.Text = strID;
                this.txtName.Text = strName;
                this.AddAttributes("OldLogoPath", Server.MapPath(oldLogo));
                this.AddAttributes("OldLogoFilename", oldLogo);
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key7", "javascript:Init_SWFUpload();", true);
            }
            catch { }
        }
        else if (e.CommandName == "DEL")
        {
            GridViewRow row = ((LinkButton)e.CommandSource).Parent.Parent as GridViewRow;
            string strID = ((Label)this.GridView1.Rows[row.RowIndex].Cells[1].FindControl("lblID")).Text.Trim();
            string oldLogo = ((HiddenField)this.GridView1.Rows[row.RowIndex].Cells[3].FindControl("hidLogo")).Value.Trim();
            this.LazyBrandBLL.DeleteBrand(strID.ToInt());
            if (File.Exists(Server.MapPath(oldLogo)))
            {
                File.Delete(Server.MapPath(oldLogo));
            }
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key7", "javascript:Init_SWFUpload();", true);
            this.BindPage(this.rptPageFliper.UniqueID, 1);
        }
    }

    private void ResetForm()
    {
        this.lblID.Text = string.Empty;
        this.txtName.Text = string.Empty;
    }
    protected void lbtnSave_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(this.lblID.Text.Trim()))
        {
            //ADD
            //if (Session["file_info"] != null)
            //{
                List<string> file_list_to_delete = new List<string>();
                try
                {
                    List<Thumbnail> thumbnails = Session["file_info"] as List<Thumbnail>;

                    string UploadPath = Server.MapPath(Misc.brand_filepath);
                    if (!System.IO.Directory.Exists(UploadPath))
                    {
                        System.IO.Directory.CreateDirectory(UploadPath);
                    }

                    string filename = string.Empty;
                    if (thumbnails != null && thumbnails.Count > 0)
                    {
                        filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(thumbnails[0].ID).ToLower();
                        file_list_to_delete.Add(Misc.brand_filepath + "/" + filename);
                        FileStream fs = new FileStream(UploadPath + "\\" + filename, FileMode.Create);
                        BinaryWriter bw = new BinaryWriter(fs);
                        bw.Write(thumbnails[0].Data);
                        bw.Close();
                        fs.Close();
                    }

                    brands.Add(new Brand()
                    {
                        BrandName = this.txtName.Text.Trim(),
                        BrandImage = (filename != string.Empty ? Misc.brand_filepath + "/" + filename : string.Empty)
                    });

                    if (this.LazyBrandBLL.InsertBrand(brands[0]))
                    {
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key1", "javascript:" + string.Format("alert('{0}');window.location.reload();", "操作成功!"), true);
                    }
                    else
                    {
                        throw new Exception("保存时发生错误");
                    }
                }
                catch (Exception ex)
                {
                    foreach (string file in file_list_to_delete)
                    {
                        if (File.Exists(Server.MapPath(file)))
                        {
                            File.Delete(Server.MapPath(file));
                        }
                    }
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key2", "javascript:" + string.Format("alert('{0}');window.location.reload();", "保存时发生错误!请重试..."), true);
                }
                finally
                {
                    Session.Remove("file_info");
                }
            //}
        }
        else
        {
            //EDIT
            string oldFilename = this.GetAttributes("OldLogoFilename");
            if (Session["file_info"] != null)
            {
                if (!System.IO.Directory.Exists(Server.MapPath(Misc.filepath)))
                {
                    System.IO.Directory.CreateDirectory(Server.MapPath(Misc.filepath));
                }
                if (!string.IsNullOrEmpty(this.GetAttributes("OldLogoPath")))
                {
                    if (File.Exists(this.GetAttributes("OldLogoPath")))
                    {
                        File.Delete(this.GetAttributes("OldLogoPath"));
                    }
                }
                List<string> file_list_to_delete = new List<string>();
                try
                {
                    List<Thumbnail> thumbnails = Session["file_info"] as List<Thumbnail>;

                    string UploadPath = Server.MapPath(Misc.brand_filepath);
                    if (!System.IO.Directory.Exists(UploadPath))
                    {
                        System.IO.Directory.CreateDirectory(UploadPath);
                    }

                    foreach (Thumbnail img in thumbnails)
                    {
                        string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(img.ID).ToLower();
                        file_list_to_delete.Add(Misc.brand_filepath + "/" + filename);
                        FileStream fs = new FileStream(UploadPath + "\\" + filename, FileMode.Create);
                        BinaryWriter bw = new BinaryWriter(fs);
                        bw.Write(img.Data);
                        bw.Close();
                        fs.Close();

                        brands.Add(new Brand()
                        {
                            BrandID = this.lblID.Text.Trim().ToInt(),
                            BrandName = this.txtName.Text.Trim(),
                            BrandImage = Misc.brand_filepath + "/" + filename
                        });
                    }
                    if (this.LazyBrandBLL.UpdateBrand(brands[0]))
                    {
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key3", "javascript:" + string.Format("alert('{0}');window.location.reload();", "操作成功!"), true);
                    }
                    else
                    {
                        throw new Exception("保存时发生错误");
                    }
                }
                catch (Exception ex)
                {
                    foreach (string file in file_list_to_delete)
                    {
                        if (File.Exists(Server.MapPath(file)))
                        {
                            File.Delete(Server.MapPath(file));
                        }
                    }
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key4", "javascript:" + string.Format("alert('{0}');window.location.reload();", "保存时发生错误!请重试..."), true);
                }
                finally
                {
                    Session.Remove("file_info");
                }
            }
            else
            {
                bool result = this.LazyBrandBLL.UpdateBrand(new Brand()
                {
                    BrandID = this.lblID.Text.Trim().ToInt(),
                    BrandName = this.txtName.Text.Trim(),
                    BrandImage = oldFilename
                });
                if (result)
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key5", "javascript:" + string.Format("alert('{0}');window.location.reload();", "操作成功!"), true);
                }
                else 
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key6", "javascript:" + string.Format("alert('{0}');window.location.reload();", "保存时发生错误!请重试..."), true);
                }
            }
        }
    }
    protected void lbtnCancel_Click(object sender, EventArgs e)
    {
        this.ResetForm();
    }
}